package com.lzx.adx.report.support.strategy.v3.media;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.CallTypeMappingDTO;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.support.strategy.v2.media.AbstractCallback;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.TOU_TIAO)
public class TouTiaoChannel extends AbstractChannel {
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, OcpxAccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        Map<String, CallTypeMappingDTO> callTypeMap = getCallTypeMap(accountDTO);
        CallTypeMappingDTO callTypeMappingDTO = callTypeMap.get(callType);
        String eventType=callTypeMappingDTO.getMediaReturnType();

        //2.从缓存加载配置
        String url = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());

        String resultUrl=url+"&event_type="+eventType;
        log.info("账号id{},请求id{} 给今日头条上报回传完整的地址：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号id{},请求id{} 给今日头条回传结果为 {}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);

        accountDTO.setFinalURL(resultUrl);
        accountDTO.setBody(result);
        return ResponseEntity.ok(new Result());
    }
}
